<?php
namespace addons\paotui\library\GatewayWorker\Applications\Paotui;
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use app\admin\model\paotui\Poster;
use app\admin\model\paotui\PosterLocation;
use app\admin\model\paotui\PostSocket;
use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    public static function onWorkerStart($businessWorker)
    {
        if($businessWorker->id === 0){
            \Workerman\Lib\Timer::add(1, function(){
                \addons\paotui\service\Socket::handleMessage();
                \addons\paotui\service\SendTemplate::send();
            });
        }

    }

    /**
     * 当客户端连接时触发
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        $message = json_encode(['type'=>'connection','clientid'=>$client_id]);
        Gateway::sendToClient($client_id, $message);
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {

        $message = json_decode($message, 1);
        if(empty($message['token'])){
            return Gateway::closeClient($client_id); //token验证失败，断开连接
        }
        $data = \addons\paotui\library\PosterToken::get($message['token']);
        if (!$data) {
            return false;
        }

        $poster_id = intval($data['poster_id']);;

        $posterModel = new Poster();
        $posterInfo = $posterModel->where(['id'=>$poster_id,'status'=>1])->find();
        if(empty($posterInfo)){
            return Gateway::closeClient($client_id); //骑手身份验证失败，断开连接
        }

        //更新最后上线状态

        if(isset($message['type'])){
            switch ($message['type']){
                case 'reg':
                    Gateway::bindUid($client_id, $posterInfo['id']);
                    $_SESSION['poster_id'] = $posterInfo['id'];
                    $posterInfo->save(['is_online'=>1,'last_online_time'=>time()]);
                    break;
                case 'heartbeat':
                    if(Gateway::isOnline($client_id)){
                        Gateway::sendToClient($client_id, json_encode(['type'=>'heartbeat','time'=>time()]));
                        if(!$posterInfo['is_online']){
                            $posterInfo->save(['is_online'=>1,'last_online_time'=>time()]);
                        }
                    }
                    break;
                case 'receive_order':       //听单
                    $status = empty($message['status'])?0:1;
                    $posterInfo->save(['is_order'=>$status]);
                    break;
                case 'sure_canel_order':
                    $postSocketModel = new PostSocket();
                    $postSocketModel->where(['post_id'=>$message['post_id'],'poster_id'=>$posterInfo['id'],'send_status'=>0])->update(['send_status'=>1]);
                    break;
                case 'location':
                    $posterLoca = new PosterLocation();
                    $posterLocaInfo = $posterLoca->where(['poster_id'=>$posterInfo['id']])->find();
                    if($posterLocaInfo){
                        $posterLocaInfo->save([
                            'lat'=>isset($message['lat'])?$message['lat']:'',
                            'lng'=>isset($message['lng'])?$message['lng']:'',
                            'updatetime'=>time()
                        ]);
                    }else{
                        $posterLocal = new PosterLocation();
                        $posterLocal->save([
                            'poster_id'=>$posterInfo['id'],
                            'lat'=>isset($message['lat'])?$message['lat']:'',
                            'lng'=>isset($message['lng'])?$message['lng']:'',
                        ]);
                    }
                    break;
            }
        }

    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        if(!empty($_SESSION['poster_id'])){
            $posterModel = new Poster();
            $posterInfo = $posterModel->where(['id'=>$_SESSION['poster_id']])->find();
            if($posterInfo){
                $posterInfo->save(['is_online'=>0,'last_offline_time'=>time()]);
            }
        }

    }

    public static function onWorkerStop($businessWorker)
    {
        $posterModel = new Poster();
        $posterModel->where(['is_online'=>1])->update(['is_online'=>0,'last_offline_time'=>time()]);
    }
}
